<?php
declare (strict_types = 1);

namespace daayu\taskload\service;

use daayu\taskload\TaskLoadConfig;

/**
 * 计划任务服务器关联Service层
 */
class TaskServerRelateService extends BaseService
{
    protected $table = 'zn_task_server_relate';

    public function list($args = [])
    {
        $page = isset($args['page']) ? intval($args['page']) : 1;
        $rows = isset($args['rows']) ? intval($args['rows']) : 20;
        $field = isset($args['field']) ? trim($args['field']) : 'id,server_id,task_id,project_id,create_time';
        $orderBy = isset($args['order_by']) ? $args['order_by'] : 'id desc';
        $where = [];
        if(isset($args['task_id']) && intval($args['task_id']) > 0){
            $where[] = ['task_id', '=', intval($args['task_id'])];
        }
        if(isset($args['server_id']) && intval($args['server_id']) > 0){
            $where[] = ['server_id', '=', intval($args['server_id'])];
        }
        if(isset($args['project_id']) && intval($args['project_id']) > 0){
            $where[] = ['project_id', '=', intval($args['project_id'])];
        }
        $rs = $this->table()->where($where)->page($page, $rows)->field($field)->order($orderBy)->select()->toArray();
        if(!empty($rs)){
            foreach($rs as $k => &$v){
            }
        }
        $ret['total'] = isset($args['total']) ? $args['total'] : $this->table()->where($where)->count();
        $ret['page'] = $page;
        $ret['rows'] = $rs;
        return $ret;
    }

    public function addServerTasks($server_ids, $task_ids)
    {
        if(empty($server_ids) || empty($task_ids)){
            $this->error = '必须同时提供server_id和task_id';
            return false;
        }
        if(!is_array($server_ids)) $server_ids = explode(',', $server_ids);
        if(!is_array($task_ids)) $task_ids = explode(',', $task_ids);
        $server_ids = array_unique(array_filter($server_ids));
        $task_ids = array_unique(array_filter($task_ids));
        $exist_server_rs = $this->table()->where('server_id', $server_ids)->field('server_id,task_id')->select();
        $exist_task_rs = $this->table(TaskLoadConfig::TABLE_TASK_PLAN)->column('project_id','id');
        $server_task_ids = [];
        foreach($exist_server_rs as $v){
            if(!isset($server_task_ids[$v['server_id']])) $server_task_ids[$v['server_id']] = [];
            $server_task_ids[$v['server_id']][] = $v['task_id'];
        }
        foreach($server_task_ids as $server_id=>$exist_relate_ids){
            $new_relate_ids = array_diff($task_ids, $exist_relate_ids);
            if(!empty($new_relate_ids)){
                $datas = [];
                foreach($new_relate_ids as $v){
                    if($v > 0) $datas[] = ['server_id'=>$server_id, 'task_id'=>$v, 'project_id'=>$exist_task_rs[$v]];
                }
                if(count($datas) > 0){
                    $rs = $this->table()->insertAll($datas);
                    if(!$rs){
                        $this->error = '新任务关联失败';
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public function updateServerTasks($server_id, $task_ids)
    {
        $server_id = intval($server_id ?? 0);
        if($server_id <= 0 || $task_ids === null){
            $this->error = '必须同时提供server_id和task_id';
            return false;
        }
        if(!is_array($task_ids)) $task_ids = explode(',', $task_ids);
        $exist_relate_ids = $this->table()->where('server_id', $server_id)->column('task_id');
        $exist_task_rs = $this->table(TaskLoadConfig::TABLE_TASK_PLAN)->column('project_id','id');
        $new_relate_ids = array_diff($task_ids, $exist_relate_ids);
        if(!empty($new_relate_ids)){
            $datas = [];
            foreach($new_relate_ids as $v){
                if($v > 0) $datas[] = ['server_id'=>$server_id, 'task_id'=>$v, 'project_id'=>$exist_task_rs[$v]];
            }
            if(count($datas) > 0){
                $rs = $this->table()->insertAll($datas);
                if(!$rs){
                    $this->error = '新任务关联失败';
                    return false;
                }
            }
        }
        $delete_relate_ids = array_diff($exist_relate_ids, $task_ids);
        if(!empty($delete_relate_ids)){
            $rs = $this->table()->where('server_id', $server_id)->where('task_id', 'in', $delete_relate_ids)->delete();
            if(!$rs){
                $this->error = '旧任务取消关联失败';
                return false;
            }
        }
        return true;
    }

    public function add($data = [])
    {
        $data['server_id'] = intval($data['server_id'] ?? 0);
        $data['task_id'] = intval($data['task_id'] ?? 0);
        if($data['server_id'] <= 0 || empty($data['task_id'])){
            $this->error = '必须同时提供server_id和task_id';
            return false;
        }
        $exist_id = $this->table()->where('server_id', $data['server_id'])->where('task_id', $data['task_id'])->value('id');
        if($exist_id){
            $this->error = '服务器已存在该任务，无需添加';
            return false;
        }
        $project_id = $this->table(TaskLoadConfig::TABLE_TASK_PLAN)->where('id', $data['task_id'])->value('project_id');
        if(empty($project_id)){
            $this->error = '无效的任务';
            return false;
        }
        $data['project_id'] = $project_id;
        $id = $this->table()->insertGetId($data);
        return $id;
    }

    public function delete($data = [])
    {
        $data['server_id'] = intval($data['server_id'] ?? 0);
        $data['task_id'] = intval($data['task_id'] ?? 0);
        if($data['server_id'] <= 0 || empty($data['task_id'])){
            $this->error = '必须同时提供server_id和task_id';
            return false;
        }
        $r = $this->table()->where('server_id', $data['server_id'])->where('task_id', $data['task_id'])->delete();
        return $r;
    }

    public function createDb()
    {
        if(!$this->checkTable()){
            $sql = "CREATE TABLE `".$this->table."`  (
                `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
                `server_id` int(11) NULL DEFAULT 0 COMMENT '服务器id',
                `project_id` int(11) DEFAULT '0' COMMENT '项目id',
                `task_id` int(11) NULL DEFAULT 0 COMMENT '计划任务id',
                `create_time` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
                PRIMARY KEY (`id`)
              ) ENGINE = InnoDB COMMENT = '服务器任务关联表' ROW_FORMAT = Dynamic";
            $this->db()->execute($sql);
        }
    }
}
